# -*- coding: utf-8 -*-


import pandas
import requests
import re
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D


# 爬取外汇数据
def get_data_from_sina(cut=0):
    """此方法是转为爬取来自新浪财经的数据而设计的"""
    url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_DINIW2019_9_25=/NewForexService.getDayKLine?symbol=DINIW&_=2019_9_25"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    response = requests.get(url=url, headers=headers)

    # print(response.text)
    '''
    var _DINIW2019_9_25=((new String("
    1985-11-08,129.2200,128.9100,129.6600,129.1300,|
    1985-11-11,129.3800,129.2200,129.4600,129.30,|
    2019-09-06,98.3769,97.9008,98.5180,97.9008,|
    2019-09-17,98.6427,98.1868,98.7450,98.2206,|
    2019-09-18,98.2181,98.1946,98.6770,98.5457,|
    2019-09-19,98.5432,98.2033,98.6249,98.3537,|
    2019-09-20,98.3508,98.1442,98.6329,98.4605,|
    2019-09-23,98.5138,98.4474,98.8407,98.6206,|
    2019-09-24,98.6232,98.2983,98.7019,98.3688,|
    2019-09-25,98.3393,98.3226,98.5849,98.5849")))    
    '''

    # string=re.findall('\((.*?)"\)"',response.text)
    # print(response.text[].replace(''))

    # 去除杂质
    newString = ''
    # shangyige = ''
    # for i in response.text:
    #     if i in '0123456789.-':
    #         newString += shangyige
    #     if i in ',':
    #         newString+='",'
    #     if i in '0123456789' and shangyige in ',':
    #         newString += '"'
    #     elif i in '0123456789' and shangyige in '|':
    #         newString+='"'
    #     shangyige=i
    # print(newString)
    for i in response.text:
        if i in '0123456789,.-|':
            newString += i
    newString = '[["' + newString.replace(',', '","').replace('","|', '"],["') + '"]]'
    newString = eval(newString)
    # print(newString)

    if cut == 0: return newString

    return newString[cut * -1:]


def show3DAaxes():
    pass
    # ax = plt.subplot(111, projection='3d')
    # ax.plot_surface(x, y, z, rstride=2, cstride=1, cmap=plt.cm.coolwarm, alpha=0.8)
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    # ax.set_zlabel('z')
    #
    # plt.show()


def showHistogram_x_y(num):
    '展示柱状图'

    def autolabel(rects):
        for rect in rects:
            height = rect.get_height()
            plt.text(rect.get_x() + rect.get_width() / 2. - 0.2, 1.03 * height, '%s' % int(height))

    name_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

    name_list = ['0.' + str(i + 1) for i in range(10)]
    num_list = [33, 44, 53, 16, 11, 17, 17, 10, 17, 10]
    name_list = num.keys()
    num_list = num.values()

    autolabel(plt.bar(range(len(num_list)), num_list, color='rgb', tick_label=name_list))
    plt.show()


def showHistogram_x(num):
    '一维列表的柱状图'

    def demo1(num):
        mu, sigma = 0, 1
        sampleNo = 1000
        np.random.seed(0)
        # s = np.random.normal(mu, sigma, sampleNo)

        s = num
        plt.hist(s, bins=100)  # , normed=True)
        plt.show()

    demo1(num)


def TimeProid():
    # 展示周期的规律
    data = get_data_from_sina()
    # print(data)

    open = [float(j[1]) for j in data]
    close = [float(j[4]) for j in data]
    high = [float(j[3]) for j in data]
    low = [float(j[2]) for j in data]
    # print(open)
    MA_60 = []
    for i in range(len(close)):
        if i < 60:
            continue
        print(close[i - 16:i])
        MA_60.append(sum(close[i - 16:i]) / 16)
    print(MA_60)
    open = open[60:]
    close = close[60:]
    high = high[60:]
    low = low[60:]
    print(len(close), len(MA_60))
    continuity = []
    disjoint_ = []
    go = 0
    intersect = 0
    disjoint = 0
    for i in range(len(MA_60)):
        if MA_60[i] < high[i] and MA_60[i] > low[i]:
            # print('相交')
            intersect += 1
            go += 0
            if disjoint != 0:
                disjoint_.append(disjoint)
            disjoint = 0
        else:
            disjoint += 1
            continuity.append(intersect)
            intersect = 0
            go += 1
    print('连续不相交的指数', disjoint_)

    showHistogram_x(disjoint_)


def Breach():
    data = get_data_from_sina()
    print(data)


if __name__ == '__main__':
    pass
    # 开盘    最低    最高    收盘
    # TimeProid()
    Breach()
